package com.wdd.atcrowdfunding.interceptor;

import com.wdd.atcrowdfunding.bean.Permission;
import com.wdd.atcrowdfunding.manager.service.PermissionService;
import com.wdd.atcrowdfunding.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //1.查询所有许可   每次访问数据可，效率低
//        List<Permission> permissions = permissionService.queryAllPermission();
//        Set<String> allURIs = new HashSet<>();
//        for(Permission permission : permissions){
//            allURIs.add("/"+permission.getUrl());
//        }

        //改进：在服务器访问时加载所有许可路劲，放入application
        Set<String> allURIs = (Set<String>) request.getSession().getServletContext().getAttribute(Const.ALL_PERMISSION_URI);


        //2.判断请求路劲是否在所有许可范围内
        String servletPath = request.getServletPath();
        if(allURIs.contains(servletPath)){
            //3.判断请求路径是否在用户拥有权限内
            Set<String> myURIs = (Set<String>) request.getSession().getAttribute(Const.MY_URIS);
            if(myURIs.contains(servletPath)){
                return true;
            }else{
                response.sendRedirect(request.getContextPath()+"/main.htm");
                return false;
            }
        }else{ // 不在拦截范围内，放行
            return true;
        }



    }
}
